package com.chenjt.activiti.utils;

import com.chenjt.activiti.ResultModel;
import org.activiti.bpmn.model.*;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 注释：流程工具类
 *
 * @author chenjt
 * @date 2022/5/12 19:50
 */
public class FlowUtils {


    private static Logger log = LoggerFactory.getLogger(FlowUtils.class);


    public static void main(String[] args) {

//        Map<String,Object> variableMap = new HashMap<>();
//        variableMap.put("assignee0","assignee0");
//        variableMap.put("assignee1","assignee1");
//        variableMap.put("assignee2","assignee2");
//        variableMap.put("assignee3","assignee3");
//        ResultModel resultModel = startProcessDefinition("inner-101", "443", variableMap);
//        String s = JSONObject.toJSONString(resultModel);
//        System.out.println(s);


//        ResultModel listMyTask = listMyTask("13352700418");
//        Object data = listMyTask.getData();
//        String s = JSONObject.toJSONString(data);
//        System.out.println(s);

//        ResultModel resultModel = completeTaskWithComment("443", "95003", "完成流程443");
//        Object data = resultModel.getData();
//        String s = JSONObject.toJSONString(data);
//        System.out.println(s);

//        ResultModel completeTaskResultModel = listCompleteTask("assignee1");
//        Object data = completeTaskResultModel.getData();
//        String s = JSONObject.toJSONString(data);
//        System.out.println(s);


//        endTask("3732818140513280","同意撤回");

//        ResultModel completeTaskByBusinessKey = listCompleteTaskByBusinessKey("3732818140513280");
//        Object data = completeTaskByBusinessKey.getData();
//        String s = JSONObject.toJSONString(data);
//        System.out.println(s);

//        recallTask("443","92503","撤回审核");

//        taskToOtherPerson("17503","assignee0");



//        deleteProcessInstance("3936621945357312","");

//        listProcessInstanceIdByBusinessKey("3936621945357312");

        getProcessVariableByBusinessKey("3469919818499072");

    }


    /**
     * 启动流程实例
     * @param processDefinitionKey 流程定义key
     * @param businessKey  业务表示
     * @param variableMap 流程变量
     * @return
     */
    public static ResultModel startProcessDefinition(String processDefinitionKey, String businessKey, Map<String,Object> variableMap){

        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        //2.得到RunService对象
        RuntimeService runtimeService = processEngine.getRuntimeService();

        //3.创建流程实例  流程定义的key需要知道 holiday

        // 判断businessKey是否已存在流程实例了，存在就不用再创建流程实例了
        List<ProcessInstance> processInstanceByBusinessKeyList = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).list();
        // businessKey已存在流程实例，不再创建流程实例了
        if(CollectionUtils.isNotEmpty(processInstanceByBusinessKeyList)){
            log.info("businessKey：" + businessKey + " 已存在流程实例，不再创建对应的流程实例");
            return ResultModel.ok("businessKey：" + businessKey + " 已存在流程实例，不再创建对应的流程实例");
        }

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey,businessKey,variableMap);


        //4.输出实例的相关信息
//        System.out.println("流程部署ID"+processInstance.getDeploymentId());//null
//        System.out.println("流程定义ID"+processInstance.getProcessDefinitionId());//holiday:1:4
//        System.out.println("流程实例ID"+processInstance.getId());//2501
//        System.out.println("活动ID"+processInstance.getActivityId());//null

        log.info("businessKey：" + businessKey + " 已存在流程实例，不再创建对应的流程实例");
        return ResultModel.ok("businessKey：" + businessKey + " 流程实例启动成功");
    }


    /**
     * 查询指定人的待办任务
     * @param assignee 指定用户
     * @return 返回该用户的任务id list
     */
    public static ResultModel listMyTask(String assignee){

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        TaskService taskService = processEngine.getTaskService();

        HistoryService historyService = processEngine.getHistoryService();

        List<Task> taskList = null;
        if("admin".equals(assignee) || "jysgzw".equals(assignee)){
            taskList = taskService.createTaskQuery()
                    .list();
        }else{
            taskList = taskService.createTaskQuery()
                    .taskAssignee(assignee).list();
        }


        List<Map<String,Object>> myTaskList = new ArrayList<>();

        taskList.forEach(task->{

            // 通过流程实例id获取businessKey，获取之后，业务端可以通过businessKey查看相关的详情

//            ACT_HI_PROCINST（历史流程实例信息）
            String processInstanceId = task.getProcessInstanceId();
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = historicProcessInstance.getBusinessKey();

            String taskId = task.getId();

            Map<String,Object> map = new HashMap<>();

            map.put("businessKey",businessKey);
            map.put("taskId",taskId);

            myTaskList.add(map);

        });

        return ResultModel.ok(myTaskList);

    }


    /**
     * 完成任务，任务拾取未做（多人完成任务的情况）
     * @param businessKey 业务标识
     * @param taskId 任务id
     * @param comment 审核意见
     * @return  processInstanceStatus: true代表流程实例已结束
     *                                 false代表流程实例还在进行中
     */
    public static ResultModel completeTaskWithComment(String businessKey,String taskId,String comment){

        //TODO 判断是否有权限完成任务

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        TaskService taskService = processEngine.getTaskService();

        RuntimeService runtimeService = processEngine.getRuntimeService();

        // 通过businessKey查询流程实例id
        Task task = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).singleResult();
        String processInstanceId = task.getProcessInstanceId();

        taskService.addComment(taskId,processInstanceId,comment);
        taskService.complete(taskId);



        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();

        boolean processInstanceStatus = false;
        Map<String,Object> tempMap = new HashMap<>();
        if(processInstance == null){
            System.out.println("流程实例" + businessKey + "已执行完毕");
            processInstanceStatus = true;
            tempMap.put("processInstanceStatus",processInstanceStatus);
        }else{
            System.out.println("流程实例" + businessKey + "正在执行");
            tempMap.put("processInstanceStatus",processInstanceStatus);
        }
        tempMap.put("processInstanceStatus",processInstanceStatus);

//        boolean processInstanceStatus = judgeProcessInstanceIsEnd(businessKey);

        String assignee = task.getAssignee();

        log.info("用户[{}]完成业务标识为[{}]的任务，意见为[{}]，流程状态[{}]",assignee,businessKey,comment,processInstanceStatus);

        return ResultModel.ok(tempMap);
    }


    /**
     * 查询指定人的已办任务
     * @param assignee 指定用户
     * @return  返回业务标识对应审核意见的list，业务端通过业务标识查询详情
     *          type: 1.comment 审核通过意见
     *                2.recall  撤回审核意见
     */
    public static ResultModel listCompleteTask(String assignee){

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        HistoryService historyService = processEngine.getHistoryService();
        TaskService taskService = processEngine.getTaskService();


        // 查询当前人的所有已办任务，获取businessKey和审核意见，业务端通过businessKey查询对应的记录详情

        List<HistoricActivityInstance> completeList = null;
        if("admin".equals(assignee) || "jysgzw".equals(assignee)){
            completeList = historyService.createHistoricActivityInstanceQuery().finished().list();
        }else{
            completeList = historyService.createHistoricActivityInstanceQuery().finished().taskAssignee(assignee).list();
        }

        List<Map<String,Object>> resultList=  new ArrayList<>();

        completeList.forEach(a->{

            //----------通过流程实例id获取businessKey----------
            String processInstanceId = a.getProcessInstanceId();

            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();

//            ACT_HI_PROCINST（历史流程实例信息）
            //----------通过流程实例id获取businessKey----------
            String businessKey = historicProcessInstance.getBusinessKey();

            String taskId = a.getTaskId();

            // 查询审核通过的审核意见
            List<Comment> taskComments = taskService.getTaskComments(taskId);

            Map<String,Object> map = new HashMap<>();

            if(CollectionUtils.isNotEmpty(taskComments)){
                // 一般情况下只会有一条审批记录
                Comment comment = taskComments.get(0);
                String fullMessage = comment.getFullMessage();

                map.put("businessKey",businessKey);
                map.put("auditComment",fullMessage);
                map.put("assignee",assignee);
                map.put("type",comment.getType());
                map.put("auditTimeStr",comment.getTime());

                resultList.add(map);
            }else{

                // 查询撤回类型的审核意见
                List<Comment> recall = taskService.getTaskComments(taskId, "recall");

                if(CollectionUtils.isNotEmpty(recall)){

                    Comment comment = recall.get(0);

                    String fullMessage = comment.getFullMessage();

                    map.put("businessKey",businessKey);
                    map.put("assignee",assignee);
                    map.put("auditComment",fullMessage);
                    map.put("type",comment.getType());
                    map.put("auditTimeStr",comment.getTime());

                    resultList.add(map);

                }

            }

        });


        return ResultModel.ok(resultList);
    }

    final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 通过businessKey查询已审批完成的任务节点（历史审批记录）
     * @param businessKey
     * @return
     *          type: 1.comment 审核通过意见
     *                2.recall  撤回审核意见
     *
     *          status: current: 当前正在审批的任务节点
     *                  history: 已经审批过的任务节点
     *                  future: 还未审批过的任务节点
     */
    public static ResultModel listCompleteTaskByBusinessKey(String businessKey){

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        HistoryService historyService = processEngine.getHistoryService();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        RuntimeService runtimeService = processEngine.getRuntimeService();


        // 查询当前待办任务
        Task currentTask = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).singleResult();


        // 当前审核节点和历史审核节点
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processInstanceBusinessKey(businessKey)
                .orderByTaskCreateTime().desc()
                .list();

        List<Map<String,Object>> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)){
            // 查找流程中所有userTask的节点
            String processDefinitionId = list.get(0).getProcessDefinitionId();
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
            List<UserTask> userTaskList = bpmnModel.getMainProcess().findFlowElementsOfType(UserTask.class);
            // 任务未结束
            if(currentTask != null){

                List<ProcessInstance> list1 = runtimeService.createProcessInstanceQuery().includeProcessVariables().processInstanceBusinessKey(businessKey).list();

                Map<String, Object> processVariables = list1.get(0).getProcessVariables();


                // --------------------- 对比当前节点处于总体流程节点的哪一步,获取后续的步骤信息 ---------------------
                Integer currentTaskIndex = null;

                for(int i = 0;i<userTaskList.size();i++){
                    if(userTaskList.get(i).getName().equals(currentTask.getName())){
                        currentTaskIndex = i;
                    }
                }

                if((userTaskList.size() - 1) != currentTaskIndex){
                    for(int a = (userTaskList.size() - 1);a >= (currentTaskIndex+1);a--){
//                for(int a = (currentTaskIndex+1);a<userTaskList.size();a++){
                        Map<String,Object> tempMap = new HashMap<>();
                        UserTask futureTask = userTaskList.get(a);
                        tempMap.put("businessKey",businessKey);

                        String futureTaskAssignee = futureTask.getAssignee();
                        if(futureTaskAssignee.indexOf("${") != -1){
                            futureTaskAssignee = futureTaskAssignee.substring(2,futureTaskAssignee.length() - 1);

                            futureTaskAssignee = processVariables.get(futureTaskAssignee) + "";

                        }

                        tempMap.put("assignee",futureTaskAssignee);
                        tempMap.put("auditComment","");
                        tempMap.put("type","comment");
                        tempMap.put("status","future");// 还未审批的节点
                        resultList.add(tempMap);
                    }
                }
                // --------------------- 对比当前节点处于总体流程节点的哪一步,获取后续的步骤信息 ---------------------


                Map<String,Object> currentTaskMap = new HashMap<>();

                currentTaskMap.put("businessKey",businessKey);
                currentTaskMap.put("assignee",currentTask.getAssignee());
                currentTaskMap.put("auditComment","");
                currentTaskMap.put("type","comment");
                currentTaskMap.put("status","current");// 当前正在审批的节点
                resultList.add(currentTaskMap);
            }
        }

        // 查询所有历史任务审批人和审批意见
        list.forEach(historicTaskInstance -> {

            Date auditTime = historicTaskInstance.getEndTime();
            String auditTimeStr = null;
            if(auditTime != null){
                auditTimeStr = sdf.format(auditTime);
            }

            String taskId = historicTaskInstance.getId();

            // ACT_HI_COMMENT
            // 查询type是comment(审核通过)的审核节点记录
            List<Comment> taskComments = taskService.getTaskComments(taskId);

            String assignee = historicTaskInstance.getAssignee();
            Map<String,Object> map = new HashMap<>();

            if(CollectionUtils.isNotEmpty(taskComments)){
                // 一般情况下只会有一条审批记录
                Comment comment = taskComments.get(0);
                String fullMessage = comment.getFullMessage();

                map.put("businessKey",businessKey);
                map.put("assignee",assignee);
                map.put("auditComment",fullMessage);
                map.put("auditTimeStr",auditTimeStr);
                map.put("type",comment.getType());
                map.put("status","history");// 历史审批的节点

                resultList.add(map);

            }else{

                // 查询撤回类型的审核意见
                List<Comment> recall = taskService.getTaskComments(taskId, "recall");

                if(CollectionUtils.isNotEmpty(recall)){

                    Comment comment = recall.get(0);

                    String fullMessage = comment.getFullMessage();

                    map.put("businessKey",businessKey);
                    map.put("assignee",assignee);
                    map.put("auditComment",fullMessage);
                    map.put("auditTimeStr",auditTimeStr);
                    map.put("type",comment.getType());
                    map.put("status","history");

                    resultList.add(map);

                }

            }

        });

        return ResultModel.ok(resultList);
    }


    /**
     * 结束任务（撤回到第一个节点）
     * @param businessKey 业务标识
     * @param comment 审核意见（撤回同意/不同意）
     */
    public static ResultModel endTask(String businessKey,String comment) {

//        String taskId = "";

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        TaskService taskService = processEngine.getTaskService();

        RepositoryService repositoryService = processEngine.getRepositoryService();

        // 一个流程实例运行期间只会有一个任务
        //TODO 这里出现重复提交的问题，会出现一个businessKey出现两个需要同时办理的任务
        // 当前任务
        Task task = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).singleResult();
//        List<Task> list = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).list();
//        Task task = list.get(0);
//        Task task1 = list.get(1);
//        String processInstanceId1 = task.getProcessInstanceId();
//        String processInstanceId2 = task1.getProcessInstanceId();



        //  当前任务
//        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        List endEventList = bpmnModel.getMainProcess().findFlowElementsOfType(EndEvent.class);
        FlowNode endFlowNode = (FlowNode) endEventList.get(0);
        FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());

        //  临时保存当前活动的原始方向
        List originalSequenceFlowList = new ArrayList<>();
        originalSequenceFlowList.addAll(currentFlowNode.getOutgoingFlows());
        //  清理活动方向
        currentFlowNode.getOutgoingFlows().clear();

        //  建立新方向
        SequenceFlow newSequenceFlow = new SequenceFlow();
        newSequenceFlow.setId("newSequenceFlowId");
        newSequenceFlow.setSourceFlowElement(currentFlowNode);
        newSequenceFlow.setTargetFlowElement(endFlowNode);
        List newSequenceFlowList = new ArrayList<>();
        newSequenceFlowList.add(newSequenceFlow);
        //  当前节点指向新的方向
        currentFlowNode.setOutgoingFlows(newSequenceFlowList);


        String taskId = task.getId();

        // 完成当前任务
        String processInstanceId = task.getProcessInstanceId();
        // type为recall是任务撤回的类型
        taskService.addComment(taskId,processInstanceId,"recall",comment);
        taskService.complete(taskId);


        //  可以不用恢复原始方向，不影响其它的流程
        currentFlowNode.setOutgoingFlows(originalSequenceFlowList);

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();

        boolean processInstanceStatus = false;
        Map<String,Object> tempMap = new HashMap<>();
        if(processInstance == null){
            System.out.println("流程实例" + businessKey + "已执行完毕");
            processInstanceStatus = true;
            tempMap.put("processInstanceStatus",processInstanceStatus);
        }else{
            System.out.println("流程实例" + businessKey + "正在执行");
            tempMap.put("processInstanceStatus",processInstanceStatus);
        }
        tempMap.put("processInstanceStatus",processInstanceStatus);

        return ResultModel.ok(tempMap);

    }


    /**
     * 任务交接
     * @param taskId 任务id
     * @param otherPerson 任务承接人(系统登录账号)
     * @return
     */
    public static ResultModel taskToOtherPerson(String taskId,String otherPerson){

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        TaskService taskService = processEngine.getTaskService();

        taskService.setAssignee(taskId,otherPerson);

        return ResultModel.ok();
    }





    /**
     * 任务撤回（退回上一个节点）
     * @param businessKey 业务标识
     * @param taskId 任务id
     * @param comment 审核意见
     * @return
     */
    public static ResultModel recallTask(String businessKey,String taskId,String comment){

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = processEngine.getRuntimeService();
//        IActHiCommentService bean = SpringUtils.getBean(IActHiCommentService.class);
//        bean.insertActHiComment()

        TaskService taskService = processEngine.getTaskService();

        RepositoryService repositoryService = processEngine.getRepositoryService();

        // 一个流程实例运行期间只会有一个任务
        // 当前任务
        Task currentTask = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).singleResult();

        BpmnModel bpmnModel = repositoryService.getBpmnModel(currentTask.getProcessDefinitionId());

        //1.-------------------------判断当前任务是否是第一个节点，是第一个节点就调用endTask()-------------------------

        List<UserTask> userTaskList = bpmnModel.getMainProcess().findFlowElementsOfType(UserTask.class);


        // 1.2--------------------- 对比当前节点处于总体流程节点的哪一步,获取后续的步骤信息 ---------------------
        Integer currentTaskIndex = null;

        for(int i = 0;i<userTaskList.size();i++){
            if(userTaskList.get(i).getName().equals(currentTask.getName())){
                currentTaskIndex = i;
            }
        }
        // 1.2--------------------- 对比当前节点处于总体流程节点的哪一步,获取后续的步骤信息 ---------------------

        if(currentTaskIndex == 0){
           return endTask(businessKey,comment);
        }

        //1.-------------------------判断当前任务是否是第一个节点，是第一个节点就调用endTask()-------------------------



        //  当前任务
//        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

//        BpmnModel bpmnModel = repositoryService.getBpmnModel(currentTask.getProcessDefinitionId());


//        List userTaskList = bpmnModel.getMainProcess().findFlowElementsOfType(UserTask.class);

        List startEventList = bpmnModel.getMainProcess().findFlowElementsOfType(StartEvent.class);


        FlowNode startFlowNode = (FlowNode) startEventList.get(0);
        FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(currentTask.getTaskDefinitionKey());

        //  临时保存当前活动的原始方向
        List originalSequenceFlowList = new ArrayList<>();
        originalSequenceFlowList.addAll(currentFlowNode.getOutgoingFlows());
        //  清理活动方向
        currentFlowNode.getOutgoingFlows().clear();

        //  建立新方向
        SequenceFlow newSequenceFlow = new SequenceFlow();
        newSequenceFlow.setId("newSequenceFlowId");
        newSequenceFlow.setSourceFlowElement(currentFlowNode);
        UserTask lastTask = userTaskList.get(currentTaskIndex - 1);
//        newSequenceFlow.setTargetFlowElement(startFlowNode);
        newSequenceFlow.setTargetFlowElement((FlowNode) lastTask);
        List newSequenceFlowList = new ArrayList<>();
        newSequenceFlowList.add(newSequenceFlow);
        //  当前节点指向新的方向
        currentFlowNode.setOutgoingFlows(newSequenceFlowList);


//        String taskId = task.getId();

        // 完成当前任务
        String processInstanceId = currentTask.getProcessInstanceId();
        // type为recall是任务撤回的类型
        taskService.addComment(taskId,processInstanceId,"recall",comment);
        taskService.complete(taskId);


        // 恢复原始方向
        currentFlowNode.setOutgoingFlows(originalSequenceFlowList);

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();

        boolean processInstanceStatus = false;
        Map<String,Object> tempMap = new HashMap<>();
        if(processInstance == null){
            System.out.println("流程实例" + businessKey + "已执行完毕");
            processInstanceStatus = true;
            tempMap.put("processInstanceStatus",processInstanceStatus);
        }else{
            System.out.println("流程实例" + businessKey + "正在执行");
            tempMap.put("processInstanceStatus",processInstanceStatus);
        }
        tempMap.put("processInstanceStatus",processInstanceStatus);

        return ResultModel.ok(tempMap);

    }




    /**
     * 判断流程实例是否已结束
     * @param businessKey
     */
    private static boolean judgeProcessInstanceIsEnd(String businessKey){

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        RuntimeService runtimeService = processEngine.getRuntimeService();

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();

        if(processInstance==null){
            System.out.println("流程实例" + businessKey + "已执行完毕");
            return true;
        }else{
            System.out.println("流程实例" + businessKey + "正在执行");
            return false;
        }

    }


    /**
     * 取得所有历史任务按时间升序排序
     */
    private static List<HistoricTaskInstance> getHistoricTaskInstanceByProcessInstanceId(String processInstanceId) {

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        HistoryService historyService = processEngine.getHistoryService();

        // 取得所有历史任务按时间升序排序
        List<HistoricTaskInstance> htiList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByTaskCreateTime()
                .asc()
                .list();
        return htiList;
    }




    private static void listProcessInstanceIdByBusinessKey(String businessKey){

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = processEngine.getRuntimeService();

        List<ProcessInstance> processInstanceByBusinessKeyList = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).list();
        System.out.println(processInstanceByBusinessKeyList.size());

    }


    /**
     * 删除流程实例
     * @param businessKey   业务表id
     * @param deleteReason    删除理由
     * @return
     */
    public static ResultModel deleteProcessInstance(String businessKey,String deleteReason){


        String processInstanceId = "";

        try {

            // 通过 businessKey 查到 processInstanceId，再通过 processInstanceId 删除流程实例
            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            RuntimeService runtimeService = processEngine.getRuntimeService();

            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();


            processInstanceId = processInstance.getProcessInstanceId();
            runtimeService.deleteProcessInstance(processInstance.getProcessInstanceId(),deleteReason);

            return ResultModel.ok("业务标识：" + businessKey + "的流程实例id：" + processInstanceId + "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultModel.ok("业务标识：" + businessKey + "的流程实例id：" + processInstanceId + "删除失败");
        }

    }


    /**
     * 通过 businessKey 获取流程实例的流程变量
     * @param businessKey
     * @return
     */
    private static ResultModel getProcessVariableByBusinessKey(String businessKey){

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = processEngine.getRuntimeService();

        List<ProcessInstance> list1 = runtimeService.createProcessInstanceQuery().includeProcessVariables().processInstanceBusinessKey(businessKey).list();

        Map<String, Object> processVariables = list1.get(0).getProcessVariables();

        System.out.println(processVariables.toString());

        return ResultModel.ok();

    }






}
